package problem273_Integer_to_English_Words;

import java.util.HashMap;
import java.util.Map;

public class Solution {
	private static Map<Integer, String> map = new HashMap<>();
	private int[] integerUnit = new int[] { 1000000000, 1000000, 1000, 100,1};
	private String[] stringUnit = new String[] { "Billion", "Million", "Thousand", "Hundred" ,""};

	static{
		fillMap();
	}
	
	public static void main(String[] args){
		System.out.println(new Solution().numberToWords(12345));
	}
	
	
	public String numberToWords(int num) {
		if(map.containsKey(num))
			return map.get(num);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < integerUnit.length; i++) {
			if (num >= integerUnit[i]) {
				int d = num / integerUnit[i];
				sb.append(convert(d) +" "+ stringUnit[i]+" ");
				num %= integerUnit[i];
			}
		}
		return sb.toString().trim();
	}

	private String convert(int num) {
		StringBuilder sb = new StringBuilder();
		if (num >= 100) {
			sb.append(map.get(num / 100) + " Hundred ");
			num %= 100;
		}
		if (num > 0) {
			if (num > 0 && num <= 20 || num % 10 == 0) {
				sb.append(map.get(num));
			} else {
				sb.append(map.get(num/10*10));
				sb.append(" "+map.get(num%10));
			}
		}
		return sb.toString().trim();
	}

	private static void fillMap() {
		map.put(0, "Zero");
		map.put(1, "One");
		map.put(2, "Two");
		map.put(3, "Three");
		map.put(4, "Four");
		map.put(5, "Five");
		map.put(6, "Six");
		map.put(7, "Seven");
		map.put(8, "Eight");
		map.put(9, "Nine");
		map.put(10, "Ten");
		map.put(11, "Eleven");
		map.put(12, "Twelve");
		map.put(13, "Thirteen");
		map.put(14, "Fourteen");
		map.put(15, "Fifteen");
		map.put(16, "Sixteen");
		map.put(17, "Seventeen");
		map.put(18, "Eighteen");
		map.put(19, "Nineteen");
		map.put(20, "Twenty");
		map.put(30, "Thirty");
		map.put(40, "Forty");
		map.put(50, "Fifty");
		map.put(60, "Sixty");
		map.put(70, "Seventy");
		map.put(80, "Eighty");
		map.put(90, "Ninety");
	}
}
